package com.ruoyi.zsyh.controller;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

import com.ruoyi.common.utils.*;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 产品补助金申请记录Controller
 * 
 * @author yuexl
 * @date 2022-01-13
 */
@Controller
@RequestMapping("/zsyh/partsQrcodeApply")
public class ZsyhPartsQrcodeApplyController extends BaseController
{
    private String prefix = "zsyh/partsQrcodeApply";

    @Value("${wxconfig.appIdAppletUser}")
    private String appIdApplet;

    @Value("${wxconfig.appSecretAppletUser}")
    private String appSecretApplet;

    @Value("${wxconfig.appIdWx}")
    private String appIdWx;

    @Value("${wxconfig.appSecretWx}")
    private String appSecretWx;

    @Value("${wxconfig.partner}")
    private String partner;

    @Value("${wxconfig.partnerKey}")
    private String partnerKey;

    @Value("${wxconfig.notifyUrlServiceOrderFixdraw}")
    private String notifyUrlServiceOrderFixdraw;

    @Autowired
    private IZsyhPartsQrcodeApplyService zsyhPartsQrcodeApplyService;
    @Autowired
    private IZsyhPlatformFactoryService zsyhPlatformFactoryService;

    @Autowired
    private IZsyhFactoryBalanceDetailsService zsyhFactoryBalanceDetailsService;
    @Autowired
    private IZsyhPlatformUserService zsyhPlatformUserService;
    @Autowired
    private IZsyhUserRepairstoreService zsyhUserRepairstoreService;

    @Autowired
    private IZsyhPartsQrcodeInstallService zsyhPartsQrcodeInstallService;

    @Autowired
    private IZsyhPartsQrcodeService zsyhPartsQrcodeService;

    @Autowired
    private IZsyhPartsApplyRecordService zsyhPartsApplyRecordService;

    @RequiresPermissions("zsyh:partsQrcodeApply:view")
    @GetMapping()
    public String partsQrcodeApply()
    {
        return prefix + "/partsQrcodeApply";
    }

    @RequiresPermissions("zsyh:partsQrcodeApply:view")
    @GetMapping("/partsQrcodeApplyReview")
    public String partsQrcodeApplyReview()
    {
        return prefix + "/partsQrcodeApplyReview";
    }

    /**
     * 查询产品补助金申请记录列表
     */
    @RequiresPermissions("zsyh:partsQrcodeApply:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ZsyhPartsQrcodeApply zsyhPartsQrcodeApply)
    {
        startPage();
        List<ZsyhPartsQrcodeApply> list = zsyhPartsQrcodeApplyService.selectZsyhPartsQrcodeApplyList(zsyhPartsQrcodeApply);
        return getDataTable(list);
    }

    /**
     * 导出产品补助金申请记录列表
     */
    @RequiresPermissions("zsyh:partsQrcodeApply:export")
    @Log(title = "产品补助金申请记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ZsyhPartsQrcodeApply zsyhPartsQrcodeApply)
    {
        List<ZsyhPartsQrcodeApply> list = zsyhPartsQrcodeApplyService.selectZsyhPartsQrcodeApplyList(zsyhPartsQrcodeApply);
        ExcelUtil<ZsyhPartsQrcodeApply> util = new ExcelUtil<ZsyhPartsQrcodeApply>(ZsyhPartsQrcodeApply.class);
        return util.exportExcel(list, "产品补助金申请记录数据");
    }

    /**
     * 新增产品补助金申请记录
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存产品补助金申请记录
     */
    @RequiresPermissions("zsyh:partsQrcodeApply:add")
    @Log(title = "产品补助金申请记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ZsyhPartsQrcodeApply zsyhPartsQrcodeApply)
    {
        return toAjax(zsyhPartsQrcodeApplyService.insertZsyhPartsQrcodeApply(zsyhPartsQrcodeApply));
    }

    /**
     * 修改产品补助金申请记录
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        ZsyhPartsQrcodeApply zsyhPartsQrcodeApply = zsyhPartsQrcodeApplyService.selectZsyhPartsQrcodeApplyById(id);
        mmap.put("zsyhPartsQrcodeApply", zsyhPartsQrcodeApply);
        return prefix + "/edit";
    }

    /**
     * 查看补助金安装信息
     */
    @GetMapping("/viewInstall/{qrcodeId}")
    public String viewInstall(@PathVariable("qrcodeId") String qrcodeId, ModelMap mmap)
    {
        ZsyhPartsQrcodeInstall zsyhPartsQrcodeInstall = zsyhPartsQrcodeInstallService.selectZsyhPartsQrcodeInstallByQrcodeId(qrcodeId);
        mmap.put("zsyhPartsQrcodeInstall", zsyhPartsQrcodeInstall);
        return prefix + "/viewInstall";
    }

    /**
     * 修改保存产品补助金申请记录
     */
    @Transactional
    @RequiresPermissions("zsyh:partsQrcodeApply:edit")
    @Log(title = "产品补助金申请记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ZsyhPartsQrcodeApply zsyhPartsQrcodeApply) throws Exception {
        ZsyhPartsQrcodeApply apply = zsyhPartsQrcodeApplyService.selectZsyhPartsQrcodeApplyById(zsyhPartsQrcodeApply.getId());
        //平台已通过
        if ("5".equals(apply.getApplyStatus())) {
            apply.setPlatformTime(DateUtils.getNowDate());
            apply.setPlatformPerson(ShiroUtils.getSysUser().getUserName());
            //给师傅进行转账
            if ("7".equals(apply.getApplyStatus())) {
                return AjaxResult.error("已核销拨款，请勿重复操作");
            }
            BigDecimal factoryBalance = apply.getFactoryBalance();//厂家余额
            BigDecimal factoryMoney = apply.getFactoryMoney();//厂家保证金
            if (factoryBalance.doubleValue() < apply.getPayPrice().doubleValue() && factoryMoney.doubleValue() < apply.getPayPrice().doubleValue()) {
                return AjaxResult.error("厂家赔付金额不足，请联系客服");
            }

            ZsyhPartsQrcodeApply apply1 = new ZsyhPartsQrcodeApply();
            apply1.setId(zsyhPartsQrcodeApply.getId());
            apply1.setIsTransfer("2");
            apply1.setApplyStatus("7");
            apply1.setTransferTime(new Date());
            apply1.setTransferPerson(ShiroUtils.getSysUser().getUserName());
            apply1.setPlatformRemarks(zsyhPartsQrcodeApply.getPlatformRemarks());

            Map<String, String> m = new HashMap<>();

            //小程序申请的需要关联user查询openid,公众号申请的时候repairedid就是openid
            String applyChannel = apply.getApplyChannel();
            String openId;
            if("1".equals(applyChannel)){
                //根据repairId获取用户信息
                String userId = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(apply.getRepairId()).getUserId();
                ZsyhPlatformUser user = zsyhPlatformUserService.selectZsyhPlatformUserById(userId);
                openId = user.getUserOpenid();
                m.put("openid", openId);
            }else if("2".equals(applyChannel)){
                openId = apply.getRepairId();
                m.put("openid", openId);
            }

            m.put("channel",applyChannel);
            m.put("orderId", zsyhPartsQrcodeApply.getId());
            m.put("money", apply.getPayPrice().toString());
//            m.put("money","0.3");//测试金额
            m.put("spbillCreateIp", "127.0.0.1");


            Map<String, Object> responseMap = null;
            //暂时屏蔽付款 TODO
            responseMap = sendPayBZJ(m);
            /*zsyhPartsQrcodeApplyService.updateZsyhPartsQrcodeApply(apply1);*/

            if (responseMap != null && responseMap.size() > 0) {
                if ("SUCCESS".equals(responseMap.get("result_code").toString())) {
                    String paymentNo = responseMap.get("payment_no").toString();
                    logger.info("调用成功");
                    //调用成功，修改申请状态，转账状态
                    apply1.setPaymentNo(paymentNo);
                    zsyhPartsQrcodeApplyService.updateZsyhPartsQrcodeApply(apply1);

                    //修改厂家余额
                    ZsyhPlatformFactory factory = new ZsyhPlatformFactory();
                    String factoryId = apply.getFactoryId();
                    factory.setId(factoryId);

                    ZsyhFactoryBalanceDetails details = new ZsyhFactoryBalanceDetails();
                    details.setFactoryId(factoryId);
                    details.setFactoryMoney(apply.getPayPrice());
                    details.setFactoryType("4");
                    details.setFactoryOrderNum(zsyhPartsQrcodeApply.getId());

                    if (factoryBalance.doubleValue() >= apply.getPayPrice().doubleValue()) {
                        factory.setFactoryBalance(factoryBalance.subtract(apply.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                        details.setFactoryClassify("2");
                        details.setFactoryBalance(factory.getFactoryBalance());
                    } else {
                        factory.setFactoryMoney(factoryMoney.subtract(apply.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                        details.setFactoryClassify("1");
                        details.setFactoryBalance(factory.getFactoryMoney());
                    }
                    zsyhPlatformFactoryService.updateZsyhPlatformFactory(factory);
                    //添加交易明细
                    zsyhFactoryBalanceDetailsService.insertZsyhFactoryBalanceDetails(details);

                    return AjaxResult.success("操作成功");
                } else {
                    String err_code = responseMap.get("err_code").toString();
                    String msg = "操作失败";
                    switch (err_code) {
                        case "AMOUNT_LIMIT":
                            msg += ",金额超限!";
                            break;
                        case "NOTENOUGH":
                            msg += ",您的付款帐号余额不足或资金未到账!";
                            break;
                        case "SYSTEMERROR":
                            msg += ",系统繁忙，请稍后再试!";
                            break;
                        case "V2_ACCOUNT_SIMPLE_BAN":
                            msg += ",用户微信支付账户未知名，无法付款!";
                            break;
                        case "SENDNUM_LIMIT":
                            msg += ",该用户今日付款次数超过限制,如有需要请登录微信支付商户平台更改API安全配置!";
                            break;
                        case "MONEY_LIMIT":
                            msg += ",已经达到今日付款总额上限/已达到付款给此用户额度上限!";
                            break;
                        case "FREQ_LIMIT":
                            msg += ",超过频率限制，请稍后再试!";
                            break;
                        default:
                            break;
                    }
                    return AjaxResult.error(msg);
                }
            }
        }else{
            apply.setPlatformPerson(ShiroUtils.getSysUser().getUserName());
            apply.setPlatformTime(new Date());
            apply.setApplyStatus(zsyhPartsQrcodeApply.getApplyStatus());
            apply.setPlatformRemarks(zsyhPartsQrcodeApply.getPlatformRemarks());
            return toAjax(zsyhPartsQrcodeApplyService.updateZsyhPartsQrcodeApply(apply));
        }
        return toAjax(zsyhPartsQrcodeApplyService.updateZsyhPartsQrcodeApply(apply));
    }


        /**
         * 维修工补助金转账
         * @param m
         * @return
         * @throws Exception
         */
        public Map<String, Object> sendPayBZJ(Map<String, String> m)throws Exception {

        String channel = m.get("channel");

        String openId = m.get("openid");
        // 1 参数
        // 订单号
        String orderId = m.get("orderId");
        // 总金额以分为单位，不带小数点
        String totalFee = StringUtils.getMoney(m.get("money"));

        // 订单生成的机器 IP
        String spbill_create_ip = m.get("spbillCreateIp");

        // ---必须参数
        // 商户号
        String mch_id = partner;
        // 随机字符串
        String nonce_str = StringUtils.getNonceStr();

        String desc = "候保配件-补助金";

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        if("1".equals(channel)){
            packageParams.put("mch_appid", appIdApplet);
        }else if("2".equals(channel)){
            packageParams.put("mch_appid", appIdWx);
        }
        packageParams.put("mchid", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("desc", desc);
        packageParams.put("partner_trade_no", orderId);
        // 这里写的金额为1 分到时修改
        packageParams.put("amount", totalFee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("check_name", "NO_CHECK");
        packageParams.put("openid", openId);

        RequestHandler reqHandler = new RequestHandler(null, null);
        if("1".equals(channel)){
            reqHandler.init(appIdApplet, appSecretApplet, partnerKey);
        }else if("2".equals(channel)){
            reqHandler.init(appIdWx, appSecretWx, partnerKey);
        }

        String sign = reqHandler.createSign(packageParams);
        logger.info("第一次签名------------------------------" + sign);
        logger.info("第一次签名------------------------------" + sign);

            Map<String, Object> map = new HashMap<>();

            String createOrderURL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
            if("1".equals(channel)){
                String xml = "<xml>" + "<mch_appid>" + appIdApplet + "</mch_appid>" + "<mchid>"
                        + mch_id + "</mchid>" + "<nonce_str>" + nonce_str
                        + "</nonce_str>"
                        + "<partner_trade_no>" + orderId + "</partner_trade_no>"
                        + "<openid>" + openId + "</openid>"
                        + "<check_name>NO_CHECK</check_name>"
                        + "<amount>" + totalFee + "</amount>"
                        + "<desc>"+ desc +"</desc>"
                        + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                        + "<sign>" + sign + "</sign>"
                        + "</xml>";
                map = new GetWxOrderno().sendPost(createOrderURL, xml);
            }else if("2".equals(channel)){
                String xml = "<xml>" + "<mch_appid>" + appIdWx + "</mch_appid>" + "<mchid>"
                        + mch_id + "</mchid>" + "<nonce_str>" + nonce_str
                        + "</nonce_str>"
                        + "<partner_trade_no>" + orderId + "</partner_trade_no>"
                        + "<openid>" + openId + "</openid>"
                        + "<check_name>NO_CHECK</check_name>"
                        + "<amount>" + totalFee + "</amount>"
                        + "<desc>"+ desc +"</desc>"
                        + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                        + "<sign>" + sign + "</sign>"
                        + "</xml>";
                map = new GetWxOrderno().sendPost(createOrderURL, xml);
            }

        logger.info("info---------------------------------------------------------获取到的预支付ID：" + map);
        logger.info("获取到的预支付ID：" + map);

        return map;
    }

    /**
     * 删除产品补助金申请记录
     */
    @Transactional
    @RequiresPermissions("zsyh:partsQrcodeApply:remove")
    @Log(title = "产品补助金申请记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        ZsyhPartsQrcodeApply zsyhPartsQrcodeApply = zsyhPartsQrcodeApplyService.selectZsyhPartsQrcodeApplyById(ids);
        int num = zsyhPartsQrcodeApplyService.deleteZsyhPartsQrcodeApplyByIds(ids);
        if(num >0){
            //删除数据的同时要删除相关图片
            if(EmptyUtils.isNotEmpty(zsyhPartsQrcodeApply.getFaultImages())){
                String[] filePath = zsyhPartsQrcodeApply.getFaultImages().split("\\|");
                for(String tempPath :filePath){
                    tempPath = tempPath.replace("https://zsyhnew.zzzsyh.com/profile","/home/zsyh/uploadPath");
                    System.out.println("path-------"+tempPath);
                    File file = new File(tempPath);
                    file.delete();
                }
            }
        }
        return toAjax(num);
    }


    /**
     * 查看主图
     */
    @GetMapping("/avatar")
    public String avatar(String attributeLogo,ModelMap mmap)
    {
        mmap.put("avatar",attributeLogo);
        return prefix + "/avatar";
    }

    /**
     * 平台审核
     */
    @GetMapping("/reviewApply/{id}")
    public String reviewApply(@PathVariable("id") String id, ModelMap mmap)
    {
        ZsyhPartsQrcodeApply zsyhPartsQrcodeApply = zsyhPartsQrcodeApplyService.selectZsyhPartsQrcodeApplyById(id);
        mmap.put("zsyhPartsQrcodeApply", zsyhPartsQrcodeApply);
        return prefix + "/reviewApply";
    }

    /**
     * 扫码查看
     */
    @GetMapping("/viewQrcode/{id}")
    public String viewQrcode(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("qrcode", id);
        return prefix + "/viewQrcode";
    }

    /**
     * 查看处理记录
     */
    @GetMapping("/viewRecord/{id}")
    public String viewRecord(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("applyId", id);
        return "zsyh/partsApplyRecord/partsApplyRecord";
    }

    /**
     * 平台审核
     */
    @GetMapping("/updateMoney/{id}")
    public String updateMoney(@PathVariable("id") String id, ModelMap mmap)
    {
        ZsyhPartsQrcodeApply zsyhPartsQrcodeApply = zsyhPartsQrcodeApplyService.selectZsyhPartsQrcodeApplyById(id);
        mmap.put("zsyhPartsQrcodeApply", zsyhPartsQrcodeApply);
        return prefix + "/updateMoney";
    }


    /**
     * 修改补贴金额
     */
    @Transactional
    @Log(title = "修改补贴金额", businessType = BusinessType.DELETE)
    @PostMapping( "/updateMoney")
    @ResponseBody
    public AjaxResult updateMoney(ZsyhPartsQrcodeApply zsyhPartsQrcodeApply)
    {
        ZsyhPartsQrcodeApply zsyhPartsQrcodeApply1 = zsyhPartsQrcodeApplyService.selectZsyhPartsQrcodeApplyById(zsyhPartsQrcodeApply.getId());
        ZsyhPartsQrcode zsyhPartsQrcode = new ZsyhPartsQrcode();
        zsyhPartsQrcode.setQrcodeId(zsyhPartsQrcodeApply1.getQrcodeId());
        zsyhPartsQrcode.setPayPrice(zsyhPartsQrcodeApply.getPayPrice());
        int num = zsyhPartsQrcodeService.updateZsyhPartsQrcode(zsyhPartsQrcode);
        return toAjax(num);
    }
}
